package com.fyt.reachgo.interceptor;


import cn.hutool.core.bean.BeanUtil;
import com.fyt.reachgo.domain.dto.UserDTO;
import com.fyt.reachgo.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.fyt.reachgo.utils.RedisConstants.LOGIN_USER_KEY;
import static com.fyt.reachgo.utils.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(RefreshTokenInterceptor.class);
    StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 取出请求头
        String token = request.getHeader("Authorization");
        token = request.getHeader("authorization");

        if (token == null) {
            log.debug("token为空");
            return true;
        }
        String tokenKey = LOGIN_USER_KEY + token;
        System.out.println("tokenkey:" + tokenKey);
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        if (userMap.isEmpty()) {
            return true;
        }

        // 将map 转为dto
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(),false);

        // 存入线程
        UserHolder.saveUser(userDTO);
        log.debug("用户信息存入线程：{}",userDTO);

        // 刷新登录时间
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }


}
